# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

__revision__ = '$Hg: packages.py,v 42004da20fdf 2007/01/01 17:22:50 +0100 $'

# system imports
import re
import time
import urllib

# DDB imports
from ddb.db import db
from ddb.tools import normalize, stripHtml, syntax
from ddb.settings import DB_REENCODE_TO
from ddb.threads import threaded

# Twisted imports
from twisted.web import client

# DDB exports
EXPORT=['Packages']

class _packagesDb(db):
    _initDb = {
        'repositories': 
        """
        CREATE TABLE repositories (distribution, version, arch, repository, releasename);
        """,
        'packages': 
        """
        CREATE TABLE packages (repositoryId, name, version, release, desciption, size, md5sum);
        """
        }

    def __init__(self):
        db.__init__(self, 'packages')

    def get(self, distribution, package):
        """Fetch a term from the package database."""
        self.cursor.execute("""
            SELECT repositories.version, repositories.repository, packages.name, packages.version, 
                   packages.release, packages.desciption, packages.md5sum, packages.size
              FROM packages, repositories
             WHERE packages.repositoryId     = repositories.rowid
               AND repositories.distribution = ?
               AND packages.name             = ?
          ORDER BY repositories.version DESC, 
                   packages.version DESC, 
                   packages.release DESC
            """, (distribution, package))
        return self.cursor.fetchall()

class Packages:
    """Various definition lookup tools."""

    ALIAS={
        'pacman':   'archlinux',
        'rpm':      'centos',
        'ebuild':   'gentoo',
        'portage':  'gentoo',
        'apt-get':  'ubuntu'
        }

    archlinux = lambda self, event: self._find(event, 'archlinux')
    centos    = lambda self, event: self._find(event, 'centos')
    gentoo    = lambda self, event: self._find(event, 'gentoo')
    ubuntu    = lambda self, event: self._find(event, 'ubuntu')

    def __init__(self):
        self.db = _packagesDb()

    @threaded
    def _find(self, event, distribution):
        """[--all] <[package]>

        Shows information about the requested package."""
        if not event.args:
            return event.reply(syntax().replace('_find', distribution))
        all = event.args.startswith('--all ')
        if all:
            package = event.args.split(' ', 1)[1]
        else:
            package = event.args
        results = list(self.db.get(distribution, package))
        if not results:
            return event.reply('Nothing was found')
        for i in range(0, len(results)):
            results[i] = list(results[i])
            for v in range(0, len(results[i])):
                if not results[i][v]:
                    results[i][v] = 'N/A'
        first = results[0]
        print first
        reply = '%s/%s: \002%s\002-%s release %s, %s, md5sum: %s, size: %s' % tuple([str(x) for x in first])
        event.reply(reply)
        if all:
            if len(results) > 1:
                rest  = results[1:]
                reply = []
                for also in rest:
                    reply.append('%s/%s %s-%s-%s' % tuple([str(x) for x in also[0:5]]))
                event.reply('Other matches: %s' % ', '.join(reply))
            else:
                event.reply('No other matches')

# vim:ts=4:sw=4:et:
